using System.Collections;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

namespace CommunityModules
{
    /// <summary>
    /// Shows a black screen over the player's view when they join (desktop and VR),
    /// fades in a welcome text, holds it, then fades everything out to reveal the world.
    /// Everything is generated at runtime and attached to the player's camera.
    /// </summary>
    public class WelcomeFadeScreen : MonoBehaviour
    {
        [Header("Text")]
        [SerializeField] private string _welcomeText = "Welcome to Progect Cloud\nPowerd By UFM";
        [SerializeField] private int _fontSize = 80;
        [SerializeField] private Color _textColor = Color.white;

        [Header("Timing (seconds)")]
        [SerializeField] private float _textFadeInDuration = 1.5f;
        [SerializeField] private float _holdDuration = 3f;
        [SerializeField] private float _fadeOutDuration = 1.5f;

        [Header("Overlay")]
        [SerializeField] private Color _backgroundColor = Color.black;
        [SerializeField] private float _distanceFromCamera = 0.6f;

        private GameObject _overlayRoot;
        private CanvasGroup _rootGroup;
        private CanvasGroup _textGroup;
        private bool _started;

        private void Update()
        {
            if (_started)
                return;

            Camera camera = Camera.main;
            if (camera == null)
                return;

            _started = true;
            BuildOverlay(camera);
            StartCoroutine(RunSequence());
        }

        private void BuildOverlay(Camera camera)
        {
            _overlayRoot = new GameObject("WelcomeFadeOverlay");
            _overlayRoot.transform.SetParent(camera.transform, false);
            _overlayRoot.transform.localPosition = new Vector3(0f, 0f, _distanceFromCamera);
            _overlayRoot.transform.localRotation = Quaternion.identity;
            _overlayRoot.transform.localScale = Vector3.one * 0.001f;

            Canvas canvas = _overlayRoot.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.WorldSpace;
            canvas.sortingOrder = 32767;

            _rootGroup = _overlayRoot.AddComponent<CanvasGroup>();
            _rootGroup.alpha = 1f;
            _rootGroup.interactable = false;
            _rootGroup.blocksRaycasts = false;

            Material overlayMaterial = new Material(Shader.Find("UI/Default"));
            overlayMaterial.SetInt("unity_GUIZTestMode", (int)CompareFunction.Always);
            overlayMaterial.renderQueue = 4999;

            GameObject blackGO = new GameObject("Black");
            blackGO.transform.SetParent(_overlayRoot.transform, false);
            RectTransform blackRect = blackGO.AddComponent<RectTransform>();
            blackRect.sizeDelta = new Vector2(20000f, 20000f);
            Image blackImage = blackGO.AddComponent<Image>();
            blackImage.color = _backgroundColor;
            blackImage.material = overlayMaterial;
            blackImage.raycastTarget = false;

            GameObject textGO = new GameObject("WelcomeText");
            textGO.transform.SetParent(_overlayRoot.transform, false);
            RectTransform textRect = textGO.AddComponent<RectTransform>();
            textRect.sizeDelta = new Vector2(1400f, 600f);
            _textGroup = textGO.AddComponent<CanvasGroup>();
            _textGroup.alpha = 0f;

            Text text = textGO.AddComponent<Text>();
            text.text = _welcomeText;
            text.font = GetDefaultFont();
            text.fontSize = _fontSize;
            text.color = _textColor;
            text.alignment = TextAnchor.MiddleCenter;
            text.horizontalOverflow = HorizontalWrapMode.Wrap;
            text.verticalOverflow = VerticalWrapMode.Overflow;
            text.raycastTarget = false;

            Material textMaterial = new Material(Shader.Find("UI/Default"));
            textMaterial.SetInt("unity_GUIZTestMode", (int)CompareFunction.Always);
            textMaterial.renderQueue = 5000;
            text.material = textMaterial;
        }

        private static Font GetDefaultFont()
        {
            Font font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            if (font == null)
                font = Resources.GetBuiltinResource<Font>("Arial.ttf");
            return font;
        }

        private IEnumerator RunSequence()
        {
            yield return Fade(_textGroup, 0f, 1f, _textFadeInDuration);
            yield return new WaitForSecondsRealtime(_holdDuration);
            yield return Fade(_rootGroup, 1f, 0f, _fadeOutDuration);

            Destroy(_overlayRoot);
            Destroy(gameObject);
        }

        private static IEnumerator Fade(CanvasGroup group, float from, float to, float duration)
        {
            if (group == null)
                yield break;

            if (duration <= 0f)
            {
                group.alpha = to;
                yield break;
            }

            float elapsed = 0f;
            while (elapsed < duration)
            {
                elapsed += Time.unscaledDeltaTime;
                group.alpha = Mathf.Lerp(from, to, Mathf.Clamp01(elapsed / duration));
                yield return null;
            }
            group.alpha = to;
        }

        private void OnDestroy()
        {
            if (_overlayRoot != null)
                Destroy(_overlayRoot);
        }
    }
}
